﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FAP.Cores.Threading;
using FAP.Cores.Task;

namespace FAP.Cores.CaptchaCenter
{
    public class CaptchaManager
    {
        private static List<CaptchaTask> m_lstCaptcha = null;

        public static void StartServer()
        {
            if (m_lstCaptcha == null)
            {
                m_lstCaptcha = new List<CaptchaTask>();
                FAP.CaptchaCenter.CaptchaServer.OnReceviceCaptcha += OnReceviceCaptcha_event;
                FAP.CaptchaCenter.CaptchaServer.StartServer();
            }
        }

        public static void GetCaptcha(CaptchaTask captchaTask)
        {
           
            m_lstCaptcha.Add(captchaTask);
            string keyWord = "FAP Captcha 123456789";

            //xu ly html

            string captChaContent = captchaTask.TaskIndex + keyWord + captchaTask.Captcha.xpath + keyWord
                + captchaTask.Captcha.html + keyWord + captchaTask.Captcha.fieldNameVerifyCaptcha;

            FAP.CaptchaCenter.CaptchaServer.SendCaptcha(captChaContent);
        }

        public static void OnReceviceCaptcha_event(string strResult)
        {
            if (strResult == "hello")
            {
                return;
            }
            //[1:59:45 PM] Châu Minh Nhựt: 1%2014%89732a7238865475883d546a5abec910
            string[] arryResult = strResult.Split('%');
            int id = Int32.Parse(arryResult[0]);
            string strCaptcha = arryResult[1];
            string strVerifyValue = "";
            if(arryResult.Length==3)
                strVerifyValue = arryResult[2];
            var task = m_lstCaptcha.Where(m => m.TaskIndex == id).SingleOrDefault();
            task.Captcha.valueVerifyCatcha = strVerifyValue;
            task.Captcha.captcha = strCaptcha;
            try
            {
                if (task == null)
                    return;
                task.onFinished(task, task.Captcha);
                m_lstCaptcha.Remove(task);
            }
            catch (Exception ex)
            {
                task.onError(task, ex);
                m_lstCaptcha.Remove(task);
            }
        }
    }
}
